package com.jeff.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.IntDef;
import android.text.TextUtils;
import android.widget.Toast;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;

/**
 * author：duff
 * version：1.0.0
 * date：2017/8/30
 */
public class ToastUtil {
    private static Toast mToast;
    private static WeakReference<Handler> mHandlerReference;

    public static void show(Context context, int resId) {
        show(context, context.getString(resId), Toast.LENGTH_SHORT);
    }

    public static void show(final Context context, final CharSequence text) {
        show(context, text, Toast.LENGTH_LONG);
    }

    public static void show(Context context, int resId, @Duration int duration) {
        show(context, context.getString(resId), duration);
    }

    public static void show(final Context context, final CharSequence text, @Duration final int duration) {
        if (context == null || TextUtils.isEmpty(text)) {
            return;
        }
        if (Looper.myLooper() != Looper.getMainLooper()) {
            if (null == mHandlerReference) {
                mHandlerReference = new WeakReference<>(new Handler(Looper.getMainLooper()));
            }
            Handler handler = mHandlerReference.get();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    show(context, text, duration);
                }
            });
        } else {
            showToast(context, text, duration);
        }
    }

    private static void showToast(Context context, CharSequence text, @Duration int duration) {
        if (mToast != null) {
            mToast.setText(text);
        } else {
            mToast = Toast.makeText(context, text, duration);
        }

        mToast.show();
    }

    @IntDef(value = {
            Toast.LENGTH_SHORT,
            Toast.LENGTH_LONG
    })
    @Retention(RetentionPolicy.SOURCE)
    public @interface Duration {
    }

}
